package dao;

import entity.SubCategory;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.transform.Transformers;
import org.hibernate.type.StandardBasicTypes;

import java.util.List;

/**
 * Created by jifeng on 2016/12/12 0012.
 */
public class SubCategoryDao {

    private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }
    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    private Session getCurrentSession() {
        return sessionFactory.getCurrentSession();
    }

    public  void  addSubCategory(SubCategory subCategory,int id){
        String sql="INSERT INTO subCategory(subCategoryName,categoryId) VALUE ('"+subCategory.getSubCategoryName()+"',"+id+")";
        getCurrentSession().createSQLQuery(sql).executeUpdate();
    }

    public List findSubCategoryList(){
        List<SubCategory> subCategoryList =null;
        String sql ="select * from SubCategory";
        subCategoryList =getCurrentSession().createSQLQuery(sql).addEntity(SubCategory.class).list();
        return subCategoryList;
    }

    public List findSubCategoryListById(int id){
        List<SubCategory> subCategoryList =null;
        String sql="select * from SubCategory s where s.categoryId ="+id+"";
       /* SQLQuery query =getCurrentSession().createSQLQuery(sql);
        query.setResultTransformer(Transformers.aliasToBean(SubCategory.class));
        subCategoryList =query.list();*/
       subCategoryList=getCurrentSession().createSQLQuery(sql).addEntity(SubCategory.class).list();
        return subCategoryList;
    }

    public SubCategory findSubCategoryById(int id){
        String sql="SELECT * FROM subCategory s WHERE s.id ="+id+"";
        List<SubCategory> subCategoryList=getCurrentSession().createSQLQuery(sql).list();
        return subCategoryList.get(0);
    }

    public void deleteSubCategory(int id){
        getCurrentSession().createQuery("delete from subCategory s where s.id ="+id+"").executeUpdate();
    }

    public void updateSub(int id,String name){
        String sql="UPDATE subCategory s SET s.subCategoryName = '"+name+"' WHERE  s.id ="+id+"";
        getCurrentSession().createSQLQuery(sql).executeUpdate();
    }
}
